<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getDynamicRouterAsync } from '@/api/services/MenuService'
import { getUserInfo } from '@/api/services/LoginService'
import type { Menu } from '@/types/Menu'

interface BubbleItem {
  id: string
  name: string
  path: string
  closable: boolean
  active: boolean
}

const router = useRouter()

// 动态菜单数据
const dynamicMenus = ref<Menu[]>([])
const menuNames = ref<Record<string, string>>({
  '/main/home': '首页'
})

// 气泡列表
const bubbles = ref<BubbleItem[]>([
  {
    id: 'home',
    name: '首页',
    path: '/main/home',
    closable: false, // 首页不可关闭
    active: true
  }
])

// 当前激活的气泡
const activeBubble = ref('home')

// 获取动态菜单并构建菜单名称映射
const fetchDynamicMenus = async () => {
  try {
    const userInfo = getUserInfo()
    if (!userInfo?.id) {
      console.error('用户信息不存在')
      return
    }

    const response = await getDynamicRouterAsync({ userId: userInfo.id })
    if (response.success && response.data) {
      dynamicMenus.value = response.data as Menu[]
      buildMenuNames(dynamicMenus.value)
    }
  } catch (error) {
    console.error('获取动态菜单异常:', error)
  }
}

// 构建菜单名称映射
const buildMenuNames = (menus: Menu[]) => {
  menus.forEach(menu => {
    menuNames.value[menu.path] = menu.meta.title
    if (menu.children && menu.children.length > 0) {
      buildMenuNames(menu.children)
    }
  })
}

// 组件挂载时获取动态菜单
onMounted(() => {
  fetchDynamicMenus()
})

// 添加或激活气泡
const addOrActivateBubble = (name: string, path: string) => {
  const existingBubble = bubbles.value.find(bubble => bubble.path === path)

  if (existingBubble) {
    // 如果气泡已存在，激活它
    activeBubble.value = existingBubble.id
    router.push(path)
  } else {
    // 创建新气泡
    const newBubble: BubbleItem = {
      id: `bubble_${Date.now()}`,
      name,
      path,
      closable: true, // 除首页外都可关闭
      active: true
    }

    // 取消其他气泡的激活状态
    bubbles.value.forEach(bubble => {
      bubble.active = false
    })

    // 添加新气泡并激活
    bubbles.value.push(newBubble)
    activeBubble.value = newBubble.id
    router.push(path)
  }
}

// 根据路径自动添加气泡
const autoAddBubble = (path: string) => {
  const menuName = menuNames.value[path] || path.split('/').pop() || '未知页面'

  // 如果是首页，不需要重复添加
  if (path === '/main/home') {
    return
  }

  const existingBubble = bubbles.value.find(bubble => bubble.path === path)

  if (!existingBubble) {
    // 创建新气泡
    const newBubble: BubbleItem = {
      id: `bubble_${Date.now()}`,
      name: menuName,
      path,
      closable: true,
      active: true
    }

    // 取消其他气泡的激活状态
    bubbles.value.forEach(bubble => {
      bubble.active = false
    })

    // 添加新气泡并激活
    bubbles.value.push(newBubble)
    activeBubble.value = newBubble.id
  } else {
    // 如果气泡已存在，激活它
    activeBubble.value = existingBubble.id
    bubbles.value.forEach(bubble => {
      bubble.active = bubble.id === existingBubble.id
    })
  }
}

// 关闭气泡
const closeBubble = (bubbleId: string, event: Event) => {
  event.stopPropagation()

  const bubbleIndex = bubbles.value.findIndex(bubble => bubble.id === bubbleId)
  if (bubbleIndex !== -1 && bubbles.value[bubbleIndex].closable) {
    // 如果要关闭的是当前激活的气泡，需要激活另一个气泡
    if (bubbles.value[bubbleIndex].active) {
      // 优先激活前一个气泡，如果没有则激活后一个
      const newActiveIndex = bubbleIndex > 0 ? bubbleIndex - 1 : bubbleIndex + 1
      if (newActiveIndex >= 0 && newActiveIndex < bubbles.value.length) {
        const newActiveBubble = bubbles.value[newActiveIndex]
        // 使用可选链操作符确保安全访问
        if (newActiveBubble?.id) {
          activeBubble.value = newActiveBubble.id
          newActiveBubble.active = true
          router.push(newActiveBubble.path)
        }
      } else {
        // 如果没有其他气泡，激活首页
        const homeBubble = bubbles.value.find(bubble => bubble.id === 'home')
        if (homeBubble) {
          activeBubble.value = 'home'
          homeBubble.active = true
          router.push('/main/home')
        }
      }
    }

    // 移除气泡
    bubbles.value.splice(bubbleIndex, 1)
  }
}

// 点击气泡切换页面
const switchBubble = (bubble: BubbleItem) => {
  if (bubble.id !== activeBubble.value) {
    // 取消其他气泡的激活状态
    bubbles.value.forEach(b => {
      b.active = b.id === bubble.id
    })

    activeBubble.value = bubble.id
    router.push(bubble.path)
  }
}

// 监听路由变化，同步气泡状态
watch(() => router.currentRoute.value.path, (newPath) => {
  // 自动添加或激活气泡
  autoAddBubble(newPath)

  // 同步激活状态
  const currentBubble = bubbles.value.find(bubble => bubble.path === newPath)
  if (currentBubble && currentBubble.id !== activeBubble.value) {
    bubbles.value.forEach(bubble => {
      bubble.active = bubble.id === currentBubble.id
    })
    activeBubble.value = currentBubble.id
  }
})

// 暴露方法给父组件
defineExpose({
  addOrActivateBubble
})
</script>

<template>
  <div class="bubble-bar">
    <div v-for="bubble in bubbles" :key="bubble.id" :class="['bubble-item', { active: bubble.active }]"
      @click="switchBubble(bubble)">
      <span class="bubble-name">{{ bubble.name }}</span>
      <span v-if="bubble.closable" class="close-text" @click="closeBubble(bubble.id, $event)">×</span>
    </div>
  </div>
</template>

<style scoped>
.bubble-bar {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 2px 0;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  overflow-x: auto;
  white-space: nowrap;
}

.bubble-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 12px;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #606266;
  user-select: none;
  height: 32px;
  line-height: 1;
  min-width: 80px;
  position: relative;
}

.bubble-item:hover {
  background: #f5f7fa;
  border-color: #c0c4cc;
}

.bubble-item.active {
  background: #409eff;
  border-color: #409eff;
  color: white;
}

.bubble-name {
  flex: 1;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 0 4px;
}

.close-text {
  font-size: 12px;
  color: #909399;
  transition: all 0.3s ease;
  cursor: pointer;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 12px;
  height: 12px;
  font-weight: bold;
  opacity: 0;
  margin-left: 4px;
  position: relative;
  top: 0;
}

.bubble-item:hover .close-text {
  opacity: 1;
}

.close-text:hover {
  color: #606266;
}

.bubble-item.active .close-text {
  color: white;
}

.bubble-item.active .close-text:hover {
  color: rgba(255, 255, 255, 0.8);
}
</style>
